﻿using UnityEngine;
using System.Collections;

public class MinimapRenderer : MonoBehaviour {
	private Texture2D tex;
	public Player test,enemy,neutral;
	public MapInfo info;
	public GameObject it1,it2;
	private IncomeTowerBehavior beh1,beh2;
	public int mapSize=256;
	// Use this for initialization
	void Start () {
		beh1 = it1.GetComponent<IncomeTowerBehavior>();
		beh2 = it2.GetComponent<IncomeTowerBehavior>();
		tex = new Texture2D(mapSize,mapSize);
		this.guiTexture.texture=tex;
	}
	
	// Update is called once per frame
	void Update () {
		erase();
		renderTerrain();			
		renderUnits ();
		tex.Apply();
	}
	void erase(){
		Color[] pix=tex.GetPixels();
		for(int i=0;i<pix.Length;i++){
			pix[i]=Color.white;
		}
		tex.SetPixels(pix);
	}
	void renderUnits(){
		double tstX,tstZ;
		int rX,rY;
		foreach(Unit u in enemy.getUnits()){
			tstX = info.convertX(u.obj.transform.position.x);
			tstZ = info.convertZ(u.obj.transform.position.z);
			rX= (int)(tstX*mapSize)-1;
			rY= (int)(tstZ*mapSize)-1;
			Color[] pixels = tex.GetPixels(rX,rY,2,2);
			for(int i=0;i<pixels.Length;i++){
				pixels[i]=Color.red;
			}
			tex.SetPixels(rX,rY,2,2,pixels);
		}
		foreach(Unit u in neutral.getUnits()){
			tstX = info.convertX(u.obj.transform.position.x);
			tstZ = info.convertZ(u.obj.transform.position.z);
			rX= (int)(tstX*mapSize)-1;
			rY= (int)(tstZ*mapSize)-1;
			Color[] pixels = tex.GetPixels(rX,rY,2,2);
			for(int i=0;i<pixels.Length;i++){
				pixels[i]=Color.black;
			}
			tex.SetPixels(rX,rY,2,2,pixels);
		}
		foreach(Unit u in test.getUnits()){
			tstX = info.convertX(u.obj.transform.position.x);
			tstZ = info.convertZ(u.obj.transform.position.z);
			rX= (int)(tstX*mapSize)-1;
			rY= (int)(tstZ*mapSize)-1;
			Color[] pixels = tex.GetPixels(rX,rY,2,2);
			for(int i=0;i<pixels.Length;i++){
				pixels[i]=Color.green;
			}
			tex.SetPixels(rX,rY,2,2,pixels);
		}
		tstX = info.convertX(it1.transform.position.x);
		tstZ = info.convertZ(it1.transform.position.z);
		rX= (int)(tstX*mapSize)-2;
		rY= (int)(tstZ*mapSize)-2;
		Color[] pix = tex.GetPixels(rX,rY,4,4);

		for(int i=0;i<pix.Length;i++){
			pix[i]=beh1.owner.myColor;
		}
		tex.SetPixels(rX,rY,4,4,pix);

		tstX = info.convertX(it2.transform.position.x);
		tstZ = info.convertZ(it2.transform.position.z);
		rX= (int)(tstX*mapSize)-2;
		rY= (int)(tstZ*mapSize)-2;
		pix = tex.GetPixels(rX,rY,4,4);
		for(int i=0;i<pix.Length;i++){
			pix[i]=beh2.owner.myColor;
		}
		tex.SetPixels(rX,rY,4,4,pix);
	}
	
	void renderTerrain(){
	
	}
}
